import React, { useEffect, useRef, useState } from "react";
import { list, delLoginLog, cleanLoginLog, exportLoginLog, unlockLoginLog } from '@/api/monitor/loginLog'
import SearchForm from "../../../components/searchForm";
import { Table, Divider, Button, message, Modal, Tag, Badge } from "antd";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { download, parseTime, rangeQueryNormalize } from "../../../utils";
import { ExclamationCircleFilled, EyeOutlined, CaretRightOutlined } from '@ant-design/icons';
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import ViewFormModal from "./modules/viewForm";

const queryItems = [
  {
    name: 'ipaddr',
    label: '登录地址',
    type: 'INPUT',
  },
  {
    name: 'msg',
    label: '操作信息',
    type: 'INPUT',
    dictType: 'sys_job_group',
  },
  {
    name: 'status',
    label: '使用状态',
    type: 'SELECT',
    dictType: 'sys_common_status',
  },
  {
    name: 'userName',
    label: '登录名称',
    type: 'INPUT',
    dictType: 'sys_job_group',
  },
  {
    name: 'beginTime-endTime',
    label: '登陆时间',
    type: 'RANGE_PICKER',
  }
];
//i18n
const LoginLogIndex = () => {
  useDictionary(['sys_common_status'])
  const viewFormModalRef = useRef()
  const [queryParam, setQueryParam] = useState({});
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [page, setPage] = React.useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '用户名称',
      dataIndex: 'userName',
      align: 'center'
    },
    {
      title: '登录地址',
      dataIndex: 'ipaddr',
      align: 'center'
    },
    {
      title: '登录地点',
      dataIndex: 'loginLocation',
      align: 'center'
    },
    {
      title: '浏览器',
      dataIndex: 'browser',
      align: 'center'
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="sys_common_status" />} />)
    },
    {
      title: '操作信息',
      dataIndex: 'msg',
      align: 'center'
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      align: 'center'
    }
  ];
  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-loginLog-list', page, queryParam],
    queryFn: () => {
      return list({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...rangeQueryNormalize(queryParam),
      }).then((res) => {
        return res?.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const cleanConfirm = () => {
    confirm({
      title: '是否确认清空?',
      icon: <ExclamationCircleFilled />,
      content: `此操作将会清空所有操作日志数据项`,
      autoFocusButton: null,
      onOk() {
        return cleanOperlog()
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('清空成功')
          })
      },
      onCancel() { },
    });
  };
  const deleteConfirm = (row) => {
    const dictIds = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return delOperlog(dictIds)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const exportConfirm = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportOperlog({
          pageNum: page.pageNo,
          pageSize: page.pageSize,
          ...queryParam,
        })
          .then(response => {
            download(response.msg)
            message.success('导出成功')
          })
      },
      onCancel() { },
    });
  }

  return (
    <div size="small" className="searchTableWrapper">
      <div className="searchTableHeader">登录日志</div>
      <SearchForm
        onSearch={(values) => setQueryParam({ ...values })}
        items={queryItems}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
      <ViewFormModal ref={viewFormModalRef} />
    </div>
  );
};


export default LoginLogIndex;
